<template>
  <div class="card">
    <div class="font-semibold text-xl mb-4">工具执行日志</div>
    <DataTable
        :value="data?.data.list"
        tableStyle="min-width: 50rem"
        selectionMode="single"
        scrollable scrollHeight="62vh"
        @row-click="showLogFunc">
      <Column field="tool_name" header="工具名称"></Column>
      <Column field="username" header="执行用户"></Column>
      <Column field="create_time" header="执行时间">
        <template #body="slotProps">
          {{ formatDate(slotProps.data.create_time) }}
        </template>
      </Column>
      <Column field="status" header="执行结果">
        <template #body="slotProps">
          <Tag v-if="slotProps.data.status === 0" value="成功" severity="success"/>
          <Tag v-else value="失败" severity="danger"/>
        </template>
      </Column>
    </DataTable>
    <Paginator :rows="10" :totalRecords="data?.data.total" :rowsPerPageOptions="[10, 20, 30]"
               @page="pageEvent"></Paginator>
  </div>
  <Dialog v-model:visible="logModalVisible" modal header="工具执行日志" :style="{ width: '60rem' }">
    <div ref="xtermContainer" style="height: 25rem"/>
  </Dialog>
</template>

<script setup>

import {useRequest} from 'ahooks-vue';
import {ApiHistoryLog} from "@/api/toolkit.js";
import {useRoute} from "vue-router";
import {ref, watch} from "vue";
import {Terminal} from "xterm";
import {FitAddon} from "xterm-addon-fit";
import 'xterm/css/xterm.css'

const route = useRoute();
const toolId = route.query._id
const username = route.query.username

const position = ref('bottom');
const align = ref('end');
const logModalVisible = ref(false)
const xtermContainer = ref()
const term = ref()
let currentContent = '';

watch(xtermContainer, (newValue) => {
  if (newValue !== undefined && newValue !== null) {
    if (term.value === undefined) {
      term.value = new Terminal({
        fontSize: 14,
        convertEol: false, // 启用时，光标将设置为下一行的开头
        rendererType: 'canvas', // 渲染类型
        cursorBlink: false, // 光标闪烁
        theme: {
          background: '#060101', // 背景色
          cursor: 'help' // 设置光标
        },
        scrollback: 10000,
      })
    }
    if (logModalVisible.value === true) {
      const fitAddon = new FitAddon();
      term.value.loadAddon(fitAddon);
      term.value.open(xtermContainer.value)
      fitAddon.fit();
      term.value.clear()
      term.value.write(currentContent)
    }
  }
})

const {data, run, loading} = useRequest(ApiHistoryLog, {
  defaultParams: [{
    tool_id: toolId,
    username: username,
    page: 0,
    page_size: 10
  }]
})

const formatDate = (value) => {
  return new Date(value).toLocaleString('zh-CN', {hour12: false});
};


const showLogFunc = (value) => {
  currentContent = value.data.content
  logModalVisible.value = true
}

const pageEvent = async (e) => {
  await run({
    tool_id: toolId,
    page: e.page,
    page_size: e.rows
  })
}

</script>

<style>
.xterm-cursor {
  visibility: hidden !important;
}
</style>